package com.gf.common.util;

import java.io.IOException;
import java.util.Date;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.commons.net.smtp.SMTPClient;
import org.apache.commons.net.smtp.SMTPReply;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.util.StringUtils;
import org.xbill.DNS.Lookup;
import org.xbill.DNS.Record;
import org.xbill.DNS.Type;

import com.dominicsayers.isemail.IsEMail;
import com.dominicsayers.isemail.IsEMailResult;
import com.dominicsayers.isemail.dns.DNSLookupException;

/**
 * 邮件发送
 * 
 * @author zhuguifeng
 * 
 */
public class MailHelper {

	private static Log logger = LogFactory.getLog(MailHelper.class);
	private final static String FROM_ADDRESS = "baibai136@163.com";
	private static final JavaMailSender MAILSENDER = SpringUtils
			.getBean("mailSender");

	/**
	 * 验证邮箱的格式<br>
	 * 检查邮箱是否真实的存在<br>
	 * 需要的jar支持：commons-net-2.2.jar，dnsjava-2.1.1.jar
	 * 此方式优点：验证出的结果，完全符合真实情况，如果一个邮箱被验证存在，那么它就一定存在，反之亦然。
	 * 此方式缺点：验证时比较耗时，我自己检测，需要5秒左右的时耗；实际情况视你自己写的发件方而定。
	 * 
	 * @param email
	 * @return true ? false
	 */
	@Deprecated
	public static boolean checkForReal(String email) {
		if (!email.matches("[\\w\\.\\-]+@([\\w\\-]+\\.)+[\\w\\-]+")) {
			return false;
		}

		String host = "";
		String hostName = email.split("@")[1];
		Record[] result = null;
		SMTPClient client = new SMTPClient();

		try {
			// 查找MX记录
			Lookup lookup = new Lookup(hostName, Type.MX);
			lookup.run();
			if (lookup.getResult() != Lookup.SUCCESSFUL) {
				return false;
			} else {
				result = lookup.getAnswers();
			}

			// 连接到邮箱服务器
			for (int i = 0; i < result.length; i++) {
				host = result[i].getAdditionalName().toString();
				//System.out.println(host + "  " + client.getReplyCode());
				client.connect(host);
				if (!SMTPReply.isPositiveCompletion(client.getReplyCode())) {
					client.disconnect();
					continue;
				} else {
					break;
				}
			}

			// 以下2项自己填写快速的，有效的邮箱
			client.login("163.com");
			client.setSender("baibai136@163.com");
			client.addRecipient(email);
			//System.out.println(client.getReplyCode());
			if (250 == client.getReplyCode()) {
				return true;
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				client.disconnect();
			} catch (IOException e) {
			}
		}
		return false;
	}

	/**
	 * 需要的jar支持：IsEMail.jar <br>
	 * 此方式优点：验证时耗时短，我自己检测，几乎立刻就可以获得结果。<br>
	 * 此方式缺点：验证出的结果，基本符合真实情况；<br>
	 * <font color='red'>此方式验证的只是邮箱表示的站点是否存在，* 至于邮箱是否真实存在则不一定。</font><br>
	 * 如***@gmail.*com格式的邮箱，则全部验证存在，但实际情况则并非如此；<br>
	 * 但提供此种邮箱服务的google站点却的确真实存在。
	 * 
	 * @param email
	 * @return
	 * @throws DNSLookupException
	 */
	@Deprecated
	public static boolean checkEmail(String email) throws DNSLookupException {
		if (!email.matches("[\\w\\.\\-]+@([\\w\\-]+\\.)+[\\w\\-]+")) {
			return false;
		}
		IsEMailResult result = IsEMail.is_email_verbose(email, true);
		switch (result.getState()) {
		case OK:
			return true;
		default:
			return false;
		}
	}

	/**
	 * 邮件发送:单纯文本
	 * 
	 * @param toAddress
	 * @param title
	 * @param content
	 */
	public static void sendSimpleMail(String toAddress, String title,
			String content) {
		SimpleMailMessage message = new SimpleMailMessage();
		message.setFrom(FROM_ADDRESS);
		message.setTo(toAddress);
		if (!StringUtils.hasLength(title)) {
			title = "无主题";
		}
		message.setSubject(title);
		message.setText(content);
		message.setSentDate(new Date());

		MAILSENDER.send(message);

		logger.debug("邮件:" + toAddress + " 发送成功!");
	}

	/**
	 * 邮件发送:html格式的文本
	 * 
	 * @param toAddress
	 * @param title
	 * @param content
	 * @throws MessagingException
	 */
	public static void sendHtmlMail(String toAddress, String title,
			String content) throws MessagingException {
		MimeMessage mimeMessage = MAILSENDER.createMimeMessage();
		MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true);
		helper.setFrom(FROM_ADDRESS);
		helper.setTo(toAddress);
		if (!StringUtils.hasLength(title)) {
			title = "无主题";
		}
		helper.setSubject(title);
		helper.setText(content, true);
		helper.setSentDate(new Date());
		MAILSENDER.send(mimeMessage);
	}

}
